import React from 'react';
import { QuestionCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Button, notification, Radio, Modal, Upload, Tooltip, Select } from 'antd';
import {
  addDataSet,
  getDataSet,
  editDataSet,
  getDataSetList,
  getDataPurpose,
} from '@/services/dataCenter';
import { baseUrl } from '@/utils/config.js'
import { checkBeforeFileUpload } from '@/utils/utils'

const { TextArea } = Input;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
    },
};


class Edit extends React.Component {
    constructor(argus) {
        super(argus);

        this.state = {
            fileList: [], // 上传文件成员
            labelled: 0, // 上传文件类型 1已标注 0未标注
            segmentType: 0, // 切分类型 1按行 0按文档
            loading: false,
            dname: '',
            desc: '',
            purpose: 0,
            purposeList: [],
            commonName: '',
            commonValue: '',
            commonAddition: '',
        };
    }

    componentDidMount() {
        const { id } = this.props;
      // eslint-disable-next-line no-unused-expressions
        Boolean(id) && getDataSet(id).then(res => {
            if (res.retCode === '0') {
                this.setState({ dname: res.data.dataSetName, desc: res.data.description })
            }
        });
      const modelPurpose = { commonType: 'model_purpose',useType:'model_purpose_data_set' };
      getDataPurpose(modelPurpose).then(rs => {
        if (rs.retCode === '0') {
          this.setState({ purposeList: rs.data })
        }
      })
    }

    // 文件类型
    filesType = e => {
        this.setState({
            labelled: e.target.value - 0,
            fileList: [],
        });
    }

    segmentType = e => {
        this.setState({
            segmentType: e.target.value - 0,
        });
    }
    // 名称校验
    onNameBlur = e => {
        const dataSetNameStrict = e.target.value.trim();
        dataSetNameStrict && getDataSetList({ data: { dataSetNameStrict } }).then(res => {
            if (res.retCode === '0') {
                if (res.data.total > 0 && res.data.list[0].dataSetId !== this.props.id) {
                    this.props.form.setFields({
                        data_set_name: {
                            value: dataSetNameStrict,
                            errors: [new Error('名称已存在!')],
                        },
                    });
                    return;
                }
            }
        })
    }

    onPurposeChange(purposeChosen) {
      this.setState({ purpose: purposeChosen });
    }

    infoToParent(key, targetId, purpose, id) {
        if (targetId == 'jumpConfig') {
            this.props.jumpConfig(purpose, id);
        } else {
            this.props.callBack(key, targetId);
        }
    }
    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        const targetId = e.target.id
        const { fileList } = this.state;
        const { id, form } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                if (!Boolean(id) && !fileList.length) {
                    this.props.form.setFields({
                        files: {
                            errors: [new Error('请先上传文件')],
                        },
                    });
                    return;
                }
                _this.setState({ loading: true, })
                if (Boolean(id)) { // 编辑
                    editDataSet({ dataSetId: id, dataSetName: values.data_set_name, description: values.description }).then(res => {
                        _this.setState({ loading: false, })
                        if (res.retCode === '0') {
                            notification['success']({
                                message: '操作成功',
                                key: '操作成功',
                                description: `数据集编辑成功`,
                            });
                            _this.infoToParent(false);
                        } else { _this.setState({ loading: false, }) }
                    });
                } else { // 新增
                    const formData = new FormData();
                    if (fileList.length == 0) {
                        _this.props.form.setFields({
                            files: {
                                errors: [new Error('请上传文件!')],
                            },
                        });
                        return;
                    }
                    fileList.forEach(file => {
                        formData.append('files', file);
                    });
                    formData.append('data_set_name', values.data_set_name);
                    formData.append('description', values.description);
                    formData.append('labelled', values.labelled - 0);
                    formData.append('data_set_segment', (values.data_set_segment - 0) || 0);
                    formData.append('purpose', values.purpose - 0);
                    addDataSet(formData).then(res => {
                        _this.setState({ loading: false, })
                        if (res.retCode === '0') {
                            notification['success']({
                                message: '操作成功',
                                key: '操作成功',
                                description: `数据集新增成功`,
                            });
                          // eslint-disable-next-line max-len
                            _this.infoToParent(false, targetId, values.purpose - 0, res.data.dataSetId);
                        }
                    });
                }
            }
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { labelled, loading, fileList, segmentType, dname, desc, purpose,purposeList } = this.state;
        const { isShowAddDataModel, id } = this.props;
        const props = {
            multiple: true,
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file, fileLists) => {
                let find = fileList.find(item => item.name === file.name);
                let isAcceptFileType = checkBeforeFileUpload(file, labelled === 1 ? ['txt', 'zip', 'json', 'doc', 'docx', 'pdf'] : ['txt', 'zip', 'doc', 'docx', 'pdf']);
                if (!isAcceptFileType.tip) {
                    notification['warning']({
                        message: '警告',
                        key: isAcceptFileType.msg,
                        description: isAcceptFileType.msg
                    });
                    return true;
                }
                if (find) {
                    notification['warning']({
                        message: '警告',
                        key: '存在同名文件',
                        description: '存在同名文件'
                    });
                    return true;
                } else {
                    if (fileLists.length > 5 - this.state.fileList.length) {
                        notification['warning']({
                            message: '警告',
                            key: '每次上传文件个数不超过5个',
                            description: '每次上传文件个数不超过5个'
                        });
                        return true;
                    } else {
                        this.setState(state => ({
                            fileList: [...state.fileList, file],
                        }));
                        return false;
                    }
                }
            },
            fileList,
        };
        return (
            <span>

                <Modal
                    title={`${Boolean(id) ? '编辑' : '新建'}数据集`}
                    maskClosable={false}
                    visible={isShowAddDataModel}
                    width={Boolean(id) ? 600 : 720}
                    onCancel={this.infoToParent.bind(this, false)}
                    footer={purpose-0===7 ? [
                      <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>
                        取消
                      </Button>,
                      <Button key="level2" type={`${(Boolean(id) || labelled || purpose == 3) ? 'primary' : 'level2'}`} id='submit' loading={loading} onClick={this.handleUserSubmit}>
                        {`${Boolean(id) ? '确定' : '完成'}`}
                      </Button>,
                    ] :[
                        <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>
                            取消
                        </Button>,
                        <Button key="level2" type={`${(Boolean(id) || labelled || purpose == 3) ? 'primary' : 'level2'}`} id='submit' loading={loading} onClick={this.handleUserSubmit}>
                            {`${Boolean(id) ? '确定' : '完成'}`}
                        </Button>,
                        <Button key="submit" type="primary" id='jumpConfig' loading={loading} onClick={this.handleUserSubmit} style={(Boolean(id) || labelled || purpose == 3) ? { display: 'none' } : null}>
                            完成并配置
                        </Button>,
                    ]}
                >
                    <Form>
                        <Form.Item label="数据集名称" {...formItemLayout}>
                            {getFieldDecorator('data_set_name', {
                                rules: [{ required: true, pattern: /^[\u4e00-\u9fa5\w]{1,16}$/, message: '数据集名称不为空、不允许特殊字符且长度不超过16!' }],
                                initialValue: dname
                            })(
                                <Input placeholder="数据集名称" onBlur={this.onNameBlur.bind(this)} />,
                            )}
                        </Form.Item>
                        <Form.Item label="数据集简介" {...formItemLayout}>
                            {getFieldDecorator('description', {
                                rules: [{ max: 200, message: '数据集简介最多200字!' }],
                                initialValue: desc
                            })(
                                <TextArea rows={3} placeholder="数据集简介，最多200字" />,
                            )}
                        </Form.Item>

                        {Boolean(id) ? null :
                            <>
                                <Form.Item label="文件类型" {...formItemLayout} onChange={this.filesType.bind(this)}>
                                    {getFieldDecorator('labelled', {
                                        rules: [{ required: true }],
                                        initialValue: '0',
                                    })(
                                        <Radio.Group>
                                            <Radio value="0">未标注</Radio>
                                            <Radio value="1">已标注</Radio>
                                        </Radio.Group>,
                                    )}
                                </Form.Item>

                                <Form.Item label='上传文件' style={{ marginBottom: 0 }} {...formItemLayout}>
                                    <div className="dropbox">
                                        {getFieldDecorator('files', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请上传文件!',
                                                },
                                            ],
                                        })(
                                            <span>
                                                <Upload {...props} accept={labelled === 1 ? ".txt,.json,.zip,.doc,.docx,.pdf" : ".txt,.zip,.doc,.docx,.pdf"}>
                                                    <Button size="small">
                                                        <UploadOutlined /> 点击上传
                                                    </Button>
                                                </Upload>
                                                {labelled === 1 ? <span style={{ padding: '6px 4px', backgroundColor: 'rgba(240, 242, 245, 1)' }}>每一个标注文本，后台将自动解析&nbsp;&nbsp;<a target='_blank' download={'模板'} className="ant-dropdown-link" type='link' href={baseUrl + '/templates/dataset'}>下载示例模板</a></span>
                                                    : <div style={{ padding: '6px 4px', backgroundColor: 'rgba(240, 242, 245, 1)', lineHeight: '24px', width: 360 }}>
                                                        <section>支持扩展名：.zip .txt .doc .docx .pdf</section>
                                                        <section>单个文件大小不超过100M</section>
                                                    </div>
                                                }
                                            </span>,
                                        )}
                                    </div>
                                </Form.Item>
                                {labelled === 1 ? null : <>
                                    <Form.Item
                                        label={
                                            <span>
                                                {'切分粒度'}
                                                <Tooltip title={'数据集切分为标注任务的切分规则。例如一篇包含10行文本的文档，使用分档划分则会生成1个标注任务。使用按行划分则会生成10个标注任务'}>
                                                    <QuestionCircleOutlined style={{ color: '#8795A1', margin: '0 2px' }} />
                                                </Tooltip>
                                            </span>
                                        } {...formItemLayout} onChange={this.segmentType.bind(this)}>
                                        {getFieldDecorator('data_set_segment', {
                                            rules: [{ required: true }],
                                            initialValue: '0',
                                        })(
                                            <Radio.Group>
                                                <Radio value="0">按文档划分</Radio>
                                                <Radio value="1">按行划分</Radio>
                                            </Radio.Group>
                                        )}
                                    </Form.Item>
                                    {segmentType === 0 && <section style={{ color: '#f50', margin: '-20px 0 0 156px' }}>按文档划分文件内容过长时，会按照一定的长度切分</section>}
                                </>
                                }
                                <Form.Item label="数据用途" {...formItemLayout}>
                                    {getFieldDecorator('purpose', {
                                        rules: [{ required: true }], initialValue: '0',
                                    })(
                                      <Select placeholder="请选择用途" showSearch onChange={this.onPurposeChange.bind(this)}>
                                        {
                                          // eslint-disable-next-line max-len
                                          purposeList.map(val => <Select.Option key={val.commonName} value={val.commonValue}>{val.commonName}</Select.Option>)
                                        }
                                      </Select>,
                                    )}
                                </Form.Item>
                            </>
                        }
                    </Form>
                </Modal>
            </span>
        );
    }
}

const DataModel = Form.create()(Edit);

export default DataModel;
